package com.xianggu.threadPool.callable;

import java.util.*;
import java.util.concurrent.*;

/**
 * 多个Callable任务并行执行
 */
public class MultipleCallableExample {
    public static void main(String[] args) {
        // 创建线程池
        ExecutorService executor = Executors.newFixedThreadPool(5);
        
        // 创建Callable任务列表
        List<Callable<String>> tasks = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            final int taskId = i;
            tasks.add(() -> {
                Thread.sleep(1000);  // 模拟耗时操作
                return "任务" + taskId + "完成，线程: " + Thread.currentThread().getName();
            });
        }
        
        try {
            // 提交所有任务并获取Future列表
            List<Future<String>> futures = executor.invokeAll(tasks);
            
            // 获取所有任务结果
            for (Future<String> future : futures) {
                System.out.println(future.get());
            }
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        } finally {
            // 关闭线程池
            executor.shutdown();
        }
    }
}